package reign.engine;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import reign.engine.exceptions.CardIDTakenException;
import reign.engine.exceptions.CardNotFoundException;
import reign.engine.structures.Card;

public class CardDirectory{

	public static HashMap<Integer,Card> namesMap;
	
	private static CardDirectory instance;
	
	private CardDirectory()
	{
		namesMap = new HashMap<Integer,Card>();
	}
	
	public static CardDirectory getInstance()
	{
		if(instance == null)
		{
			instance = new CardDirectory();
		}
		return instance;
	}
	
	public  synchronized Card getByID(int id) throws CardNotFoundException
	{
		Card returnMe = namesMap.get(id);
		if(returnMe != null)
		{
			throw new CardNotFoundException("No Card Exists with ID Number: " + id);
		}
		return returnMe;
	}
	
	public  synchronized void addCard(Card addMe) throws CardIDTakenException
	{
		Card returnMe = namesMap.get(addMe.getID());
		if(returnMe != null)
		{
			throw new CardIDTakenException("No Card Exists with ID Number: " + addMe.getID());
		}
		namesMap.put(addMe.getID(), addMe);
	}
	
	public  synchronized Card forceAddCard(Card addMe)
	{
		Card returnMe = namesMap.get(addMe.getID());
		namesMap.put(addMe.getID(), addMe);
		return returnMe;
	}
	
	public  synchronized void clearMap()
	{
		namesMap.clear();
	}
	
	public String toString()
	{
		StringBuilder out = new StringBuilder();
		Iterator<Entry<Integer, Card>> entries = namesMap.entrySet().iterator();
		while(entries.hasNext())
		{
			Entry<Integer,Card> tempEntry = entries.next();
			out.append("Key: " + tempEntry.getKey().toString() + " Value: " + tempEntry.getValue().getName() + "\n");
		}
		return out.toString();
	}
	
}
